let jwt = require('jsonwebtoken');

module.exports = () => {
    return async (ctx,next) => {
        //1.白名单
        let writePath = ['/api/login','/api/registry'];

        if(writePath.includes(ctx.path)){
            //2.1不校验
            await next();
        }else{
            //2.2校验token
            //2.2.1 获取token header里传过来的token
            let token = ctx.get('token');
            try{
                ctx.info = jwt.verify(token,'1710A');
                console.log("=====",ctx.info)
                await next();
            }catch(e){
                //e:错误对象  如果是token的错误  把状态码设置为401

                if(e.name === 'TokenExpiredError' || e.name === 'JsonWebTokenError'){
                    //token有误
                    ctx.status = 401;
                    ctx.body = {
                        code:4,
                        msg:e
                    }
                }else{
                    ctx.body = {
                        code:0,
                        msg:e
                    }
                }
            }
        }
    }
}